# coding: utf-8
import sys, os
import numpy as np
import pandas as pd
# pd.set_option('display.max_columns',1000)
# pd.set_option('display.width', 1000)
# pd.set_option('display.max_colwidth',1000)
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 
import pickle
from mnist import load_mnist
from common.functions import sigmoid, softmax


def get_data():
    (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)
    # normalize如果设置为False,那么输入图像的像素会保持原来的0~255.否则将输入图像正规化为0.0~1.0的值.
    # flattern的意思是:是否展开图像,如果该参数设置为False,则输入图像为1x28x28的三维数组
    return x_test, t_test


def init_network():#读取初始权重
    with open("sample_weight.pkl", 'rb') as f:
        network = pickle.load(f)#network的类型是dict
    return network


def predict(network, x):#通过已有的模型进行计算,得到预测结果,然后输出结果中,哪个结果的数值最大就认为是数字几,当然,输出节点都是在训练前就按照数字的大小进行排序的.
    # print("x=",x)
    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']

    a1 = np.dot(x, W1) + b1
    z1 = sigmoid(a1)
    a2 = np.dot(z1, W2) + b2
    z2 = sigmoid(a2)
    a3 = np.dot(z2, W3) + b3
    y = softmax(a3)
    return y


if __name__ == '__main__':
    x, t = get_data()#这里的x是裸数据,t是类别,
    network = init_network()#这里是在训练神经网络模型
    accuracy_cnt = 0
    for i in range(len(x)):
        y = predict(network, x[i])
        p= np.argmax(y) # 获取概率最高的元素的索引,这里的y是一个数组,索引代表第几类,也代表第几个数字,因为这里是数字手写图片识别
        if p == t[i]:#将预测的类别和数据的实际类别进行比较
            accuracy_cnt += 1#如果预测准确就+1
    print("Accuracy:" + str(float(accuracy_cnt) / len(x)))